import React, { useEffect, useRef, useState } from 'react';

// 自定义组件
import DX5S from '../LEAFLET_SDK';
// styles
import styles from './index.less';
let map = null;
const LeafletComponent = () => {
  const mapEle = useRef(null);

  const initMap = () => {
    const options = {
      center: [18.74, 116.94],
      zoom: 5,
    };
    if (mapEle.current) {
      const viewer = new DX5S.LFTCanvas(mapEle.current, options);
      // console.log('viewer', viewer);
      // 添加基础图层
      map = viewer._map;
      L._map = map;
      window.LFTmap = map;
      window.LFTViewer = viewer;
      L.tileLayer(
        'http://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
      ).addTo(map);

      // 获取 zoomControl 控件
      const zoomControl = map.zoomControl;
      // 隐藏 zoomControl
      zoomControl.remove();
    }
  };

  const detectWebGLContext = () => {
    const canvas = document.createElement('canvas');
    const gl =
      canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
    if (gl && gl instanceof WebGLRenderingContext) {
      return true;
    } else {
      console.log('不支持WEBGL');
    }
  };

  useEffect(() => {
    initMap();
    detectWebGLContext();
    return () => {
      mapEle.current = null;
      window.map && window.map.remove();
      window.map = null;
    };
  }, []);

  return <div className={styles.mapContainer} ref={mapEle}></div>;
};

export default LeafletComponent;
